package l1j.server.server.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Timestamp;

import l1j.server.DatabaseFactory;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.datatables.lock.CharItemsReading;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.templates.L1Beginner;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

// Referenced classes of package l1j.server.server.model:
// L1PcInstance

public class BeginnerTable {

	private static Logger _log = Logger.getLogger(BeginnerTable.class.getName());

	private static BeginnerTable _instance;

	private static final Map<String, ArrayList<L1Beginner>> _beginnerList =
			new HashMap<String, ArrayList<L1Beginner>>();

	public static BeginnerTable get() {
		if (_instance == null) {
			_instance = new BeginnerTable();
		}
		return _instance;
	}

	private void add(final L1Beginner beginner) {
		final String key = beginner.get_activate();
		ArrayList<L1Beginner> list = _beginnerList.get(key);
		if (list == null) {
			list = new ArrayList<L1Beginner>();
			list.add(beginner);

		} else {
			list.add(beginner);
		}
		_beginnerList.put(key, list);
	}

	/*public int GiveItem(final L1PcInstance pc) {
		Connection con = null;
		PreparedStatement pstm1 = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm1 = con
			.prepareStatement("SELECT * FROM beginner WHERE activate IN(?,?)");

			pstm1.setString(1, "A");
			if (pc.isCrown()) {
				pstm1.setString(2, "P");
			} else if (pc.isKnight()) {
				pstm1.setString(2, "K");
			} else if (pc.isElf()) {
				pstm1.setString(2, "E");
			} else if (pc.isWizard()) {
				pstm1.setString(2, "W");
			} else if (pc.isDarkelf()) {
				pstm1.setString(2, "D");
			} else if (pc.isDragonKnight()) { // ドラゴンナイト
				pstm1.setString(2, "R");
			} else if (pc.isIllusionist()) { // イリュージョニスト
				pstm1.setString(2, "I");
			} else {
				pstm1.setString(2, "A");// 万が一どれでもなかった場合のエラー回避用
			}
			rs = pstm1.executeQuery();

			while (rs.next()) {
				PreparedStatement pstm2 = null;
				try {
					pstm2 = con.prepareStatement("INSERT INTO character_items SET id=?, item_id=?, char_id=?, item_name=?, count=?, is_equipped=?, enchantlvl=?, is_id=?, durability=?, charge_count=?, remaining_time=?, last_used=?, bless=?, DeleteDate=?");
					pstm2.setInt(1, IdFactory.getInstance().nextId());
					pstm2.setInt(2, rs.getInt("item_id"));
					pstm2.setInt(3, pc.getId());
					pstm2.setString(4, rs.getString("item_name"));
					pstm2.setInt(5, rs.getInt("count"));
					pstm2.setInt(6, 0);
					pstm2.setInt(7, rs.getInt("enchantlvl"));
					pstm2.setInt(8, 1);//鑑定
					pstm2.setInt(9, 0);
					pstm2.setInt(10, rs.getInt("charge_count"));
					pstm2.setInt(11, 0);
					pstm2.setTimestamp(12, null);
					pstm2.setInt(13, rs.getInt("bless"));//TODO 新增欄位bless0:祝福 1:普通狀態 2:詛咒)
					// 道具天數刪除系統
					int delday = rs.getInt("DeleteDay");
					if (delday != 0) {
						Timestamp deleteDay = new Timestamp(System.currentTimeMillis()+ (86400000 * delday));
						pstm2.setTimestamp(14, deleteDay);
					} else {
						pstm2.setTimestamp(14, null);
					}
					pstm2.execute();
				} catch (final SQLException e2) {
					_log.log(Level.SEVERE, e2.getLocalizedMessage(), e2);
				} finally {
					SQLUtil.close(pstm2);
				}
			}
		} catch (final SQLException e1) {
			_log.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm1);
			SQLUtil.close(con);
		}
		return 0;
	}*/
	/**
	 * 給予物品
	 * @param objid
	 * @param beginner
	 */
	private void get_item(final int objid, final L1Beginner beginner) {
		try {
			final L1ItemInstance item = ItemTable.getInstance().createItem(beginner.get_itemid());
			if (item != null) {
				item.setIdentified(true);
				item.setCount(beginner.get_count());
				item.setEnchantLevel(beginner.get_enchantlvl());
				item.setChargeCount(beginner.get_charge_count());
				item.setBless(item.getBless());
				final int delday = beginner.get_time();
				if (delday != 0) {
					final Timestamp deleteDay = new Timestamp(System.currentTimeMillis()+ 86400000 * delday);
					item.setDeleteDate(deleteDay);
				}
				CharItemsReading.get().storeItem(objid, item);
//				if (beginner.get_time() > 0) {
//					long time = System.currentTimeMillis();// 目前時間豪秒
//					long x1 = beginner.get_time() * 60 * 60;// 指定小時耗用秒數
//					long x2 = x1 * 1000;// 轉為豪秒
//					long upTime = x2 + time;// 目前時間 加上指定天數耗用秒數

//					// 時間數據
//					final Timestamp ts = new Timestamp(upTime);
//					item.set_time(ts);
//
//					// 人物背包物品使用期限資料
//					CharItemsTimeReading.get().addTime(item.getId(), ts);
//				}
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
	}
	public void giveItem(final L1PcInstance pc) {
		String key = "A";
		if (pc.isCrown()) {// 王族
			key = "P";

		} else if (pc.isKnight()) {// 騎士
			key = "K";

		} else if (pc.isElf()) {// 精靈
			key = "E";

		} else if (pc.isWizard()) {// 法師
			key = "W";

		} else if (pc.isDarkelf()) {// 黑妖
			key = "D";

		} else if (pc.isDragonKnight()) {// 龍騎士
			key = "R";

		} else if (pc.isIllusionist()) {// 幻術師
			key = "I";
		}

		final ArrayList<L1Beginner> list = _beginnerList.get(key);
		if (list != null) {
			if (!list.isEmpty()) {
				for (final L1Beginner beginner : list) {
					this.get_item(pc.getId(), beginner);
				}
			}
		}

		final ArrayList<L1Beginner> listAll = _beginnerList.get("A");
		if (listAll != null) {
			if (!listAll.isEmpty()) {
				for (final L1Beginner beginner : listAll) {
					this.get_item(pc.getId(), beginner);
				}
			}
		}
	}


	public void load() {
		final PerformanceTimer timer = new PerformanceTimer();
		int i = 0;
		Connection cn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			cn = DatabaseFactory.get().getConnection();
			ps = cn.prepareStatement("SELECT * FROM `beginner`");
			rs = ps.executeQuery();
//pstm2 = con.prepareStatement("INSERT INTO character_items SET id=?, item_id=?, char_id=?, item_name=?, count=?, is_equipped=?, enchantlvl=?, is_id=?, durability=?, charge_count=?, remaining_time=?, last_used=?, bless=?, DeleteDate=?");

			while (rs.next()) {
				final String activate = rs.getString("activate").toUpperCase();
				final int itemid = rs.getInt("item_id");
				final int count = rs.getInt("count");
				final int charge_count = rs.getInt("charge_count");
				final int enchantlvl = rs.getInt("enchantlvl");
				final int bless = rs.getInt("bless");
				// 道具天數刪除系統
				final int delday = rs.getInt("DeleteDay");

				if (count > 0) {
					final L1Beginner beginner = new L1Beginner();
					beginner.set_activate(activate);
					beginner.set_itemid(itemid);
					beginner.set_count(count);
					beginner.set_enchantlvl(enchantlvl);
					beginner.set_charge_count(charge_count);
					beginner.set_bless(bless);
					beginner.set_time(delday);

					this.add(beginner);
					i++;
				}
			}

		} catch (final SQLException e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(ps);
			SQLUtil.close(cn);
		}
		_log.info("載入新手物品資料數量: " + _beginnerList.size() + "/" + i + "(" + timer.get() + "ms)");
	}
}